<template>
  <div class="app-fill-page">
    <div id="main">
      <el-form ref="formRef" class="login-form" label-width="100px" label-position="left" :model="form" :rules="rules" :scroll-to-error="true">
        <h2 id="title">Spark外卖-商家入驻</h2>
        <el-form-item class="el-form-item" label="店铺名称：" prop="name">
          <el-input type="text" placeholder="请输入店铺的名称..." v-model="form.name"> </el-input>
        </el-form-item>
        <el-form-item class="el-form-item" label="店铺封面：" prop="logo">
          <oss-upload v-model="form.logo"></oss-upload>
        </el-form-item>
        <el-form-item class="el-form-item" label="店内图片：">
          <oss-upload v-model="form.backgroundPoster"></oss-upload>
        </el-form-item>
        <el-form-item class="el-form-item" label="店铺位置：">
          <region v-model="form" v-model:regionLabel="regionLabel" />
        </el-form-item>
        <el-form-item class="el-form-item" label="详细地址：" prop="addressDescribe">
          <el-input type="text" placeholder="补充店铺详细地址..." v-model="form.addressDescribe"> </el-input>
        </el-form-item>
        <el-form-item class="el-form-item" label="具体位置：">
          <BMap
            width="100%"
            height="200px"
            class="map"
            :zoom="zoom"
            enableScrollWheelZoom
            ref="map"
            :center="point || undefined"
            @initd="refreshMarker"
          >
            <BControl style="display: flex; padding: 10px; background-color: #fff" :offset="{ x: 0, y: 0 }">
              <el-button size="small" @click="zoomControl(-1)" class="zoom_control_button">缩小</el-button>
              <el-button size="small" @click="zoomControl(1)" class="zoom_control_button">放大</el-button>
              <el-button size="small" @click="refreshMarker()">刷新<span v-if="isLoading">（正在刷新...）</span></el-button>
            </BControl>
            <template v-if="!isLoading">
              <BMarker :position="point" enableDragging @dragend="onDragend" @initd="onMapMarkInitd"></BMarker>
            </template>
          </BMap>
        </el-form-item>
        <el-form-item class="el-form-item" label="店铺类型" prop="shopCategory">
          <el-select class="m-2" placeholder="类型选择" v-model="form.shopCategoryId">
            <el-option v-for="item in shopCategoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="el-form-item" label="手机号码：" prop="phone">
          <el-input type="text" placeholder="请输入店主的联系手机号码（登录账号）... " v-model="form.phone"> </el-input>
          <div class="phone_code">
            <el-input type="text" placeholder="请输入下发的验证码... " class="code_input" v-model="form.phoneCode"></el-input>
            <el-button @click="sendSettleInCode()" :disabled="isDisableSendPhoneCodeButten">{{
              isDisableSendPhoneCodeButten ? `重新发送(${remainingVerificationCodeTime})` : '发送验证码'
            }}</el-button>
          </div>
        </el-form-item>

        <el-form-item class="el-form-item" label="店铺代表人身份证：">
          <oss-upload v-model="form.idCardImage"></oss-upload>
        </el-form-item>
        <el-form-item class="el-form-item" label="营业执照：">
          <oss-upload v-model="form.businessLicenseImage"></oss-upload>
        </el-form-item>
        <el-form-item class="el-form-item" label="食品安全许可证：">
          <oss-upload v-model="form.permitImage"></oss-upload>
        </el-form-item>
        <el-button type="primary" id="submit" @click="submitRegister(formRef)">提交注册开店</el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { BMap, useAddressGeocoder, Point } from 'vue3-baidu-map-gl'
import { reactive, ref, getCurrentInstance, watch } from 'vue'
import ossUpload from '@/components/oss-upload/index.vue'
import { SettleInParam } from '@/types/param/settle-in'
import { ShopCategory } from '@/types/response/shop-category.ts'
import region from '@/components/region/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { RegionLabelType } from '@/components/region/RegionType.ts'
import ComponentHat from '@/plugins/type'
import { useRouter } from 'vue-router'
const router = useRouter()
const { $modal, $API } = <ComponentHat>getCurrentInstance().proxy
const form = ref(new SettleInParam())
const shopCategoryList = ref<ShopCategory[]>()
const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '店铺的名称不能为空',
      trigger: 'blur'
    },
    {
      trigger: ['blur', 'change'],
      pattern: /.{2}/,
      message: '不能少于2位字符'
    }
  ],
  logo: [{ trigger: ['blur', 'change'], pattern: /^https:\/\/.*/, message: '店铺封面logo未上传' }],
  addressDescribe: [{ trigger: ['blur', 'change'], required: true, message: '详细地址不能为空' }],
  phone: [
    {
      trigger: ['blur', 'change'],
      pattern: /\d{11}/,
      message: '手机号必须为11位数字'
    }
  ]
})
const formRef = ref<FormInstance>()
const zoom = ref(15)
const map = ref()
const { get, point, isLoading } = useAddressGeocoder<Point>(() => {
  map.value.resetCenter()
})
const regionLabel = ref(new RegionLabelType())
watch(
  () => [regionLabel.value, form.value.addressDescribe],
  () => {
    // 同步修改form
    form.value.provinceName = regionLabel.value.provinceName
    form.value.cityName = regionLabel.value.cityName
    form.value.districtName = regionLabel.value.districtName
    // 刷新地图marker
    refreshMarker()
  },
  { deep: true }
)
function refreshMarker() {
  if (regionLabel.value.provinceName == null) {
    get('故宫', '北京市')
  } else {
    get(
      `${regionLabel.value.districtName ?? ''}${form.value.addressDescribe ?? ''}` ?? '政府',
      `${regionLabel.value.provinceName ?? ''}${regionLabel.value.cityName} ??''`
    )
  }
}
function zoomControl(addValue: number) {
  zoom.value = zoom.value + addValue > 19 ? 19 : zoom.value + addValue
}
function onDragend(e: { latLng: { lat: number; lng: number } }): void {
  form.value.latitude = e.latLng.lat
  form.value.longitude = e.latLng.lng
}

// 定义一个类型，表示一个接受两个数字参数的函数，并返回一个数字。
type AddFunction = (num1: number, num2: number) => number

// 使用 AddFunction 类型修饰我们的 add 函数。
const add: AddFunction = (a, b) => {
  return a + b
}

// 地图标记初始化事件
type MarkInitd = (e: {
  instance: {
    point: { lng: number; lat: number }
  }
}) => void
const onMapMarkInitd: MarkInitd = (e) => {
  form.value.latitude = e.instance.point.lat
  form.value.longitude = e.instance.point.lng
}
let isDisableSendPhoneCodeButten = ref(false)
const defaultRemainingVerificationCodeTime = ref(60)
let remainingVerificationCodeTime = ref(defaultRemainingVerificationCodeTime.value)
function resetSendPhoneCodeButtenStatus() {
  isDisableSendPhoneCodeButten.value = false
  remainingVerificationCodeTime.value = defaultRemainingVerificationCodeTime.value
}
async function sendSettleInCode() {
  isDisableSendPhoneCodeButten.value = true
  let timer: number = null
  timer = setInterval(() => {
    if (--remainingVerificationCodeTime.value === 0) {
      clearInterval(timer)
      resetSendPhoneCodeButtenStatus()
    }
  }, 1000)
  const result = await $API.shop.sendSettleInPhoneCode(form.value.phone)
  if (!result.success) {
    $modal.msgWarning(result.message)
    clearInterval(timer)
    resetSendPhoneCodeButtenStatus()
  }
}
// 初始化店铺分类
$API.shopCategory.listAll().then((result) => {
  if (result.success) shopCategoryList.value = result.data
})
function submitRegister(formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('提交注册的信息：', form)
      const result = await $API.shop.settleIn(form.value)
      if (!result.success) {
        $modal.msgWarning(result.message)
      } else {
        // 跳转成功页
        router.push({ path: '/success' })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped>
.app-fill-page {
  padding: 20px 10%;
  background: #f7f7f7;
}

#title {
  line-height: 50px;
  font-size: 26px;
  text-align: center;
}

#main {
  background: #fff;
  box-shadow: 0 0 3px 1px rgb(0 0 0 / 10%);

  .login-form {
    margin: 0 auto;
    padding: 20px;
    box-sizing: border-box;
    width: 600px;
    max-width: 90%;

    .shop_address {
      display: flex;
      justify-content: center;
    }

    #submit {
      display: block;
      margin: 0 auto;
    }
  }
}

.map {
  width: 100%;
  height: 200px;
}

.phone_code {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 5px;
  width: 100%;

  .code_input {
    flex-grow: 1;
    padding-right: 5px;
  }
}
</style>
